//公用的函数
"use strict";
var vw_static = function() {
	var _hashMap = {
		Set: function(key, value) {
			this[key] = value
		},
		Get: function(key) {
			return this[key]
		},
		Contains: function(key) {
			return this.Get(key) == null ? false : true
		},
		Remove: function(key) {
			delete this[key]
		}
	};

	function quickSort(arr, col) {
		//如果数组长度小于等于1无需判断直接返回即可  
		if(arr.length <= 1) {
			return arr;
		}
		var midIndex = Math.floor(arr.length / 2); //取基准点  
		var midIndexVal = arr.splice(midIndex, 1)[0]; //取基准点的值,splice(index,1)函数可以返回数组中被删除的那个数arr[index+1]  
		var left = []; //存放比基准点小的数组  
		var right = []; //存放比基准点大的数组  
		//遍历数组，进行判断分配  
		for(var i = 0; i < arr.length; i++) {
			if(parseFloat(arr[i].content[col]) < parseFloat(midIndexVal.content[col])) {
				left.push(arr[i]); //比基准点小的放在左边数组  
			} else {
				right.push(arr[i]); //比基准点大的放在右边数组  
			}
		}
		//递归执行以上操作,对左右两个数组进行操作，直到数组长度为<=1；  
		return quickSort(left, col).concat(midIndexVal, quickSort(right, col));
	}

	//自定义事件
	var _event = {
		// 通过on接口监听事件eventName，如果事件eventName被触发，则执行callback回调函数
		on: function(eventName, callback) {
			if(!this.handles) {
				this.handles = {};
			}
			if(!this.handles[eventName]) {
				this.handles[eventName] = [];
			}
			this.handles[eventName].push(callback);
		},
		// 触发事件 eventName
		trigger: function(eventName) {
			if(!this.handles) {
				this.handles = {};
			}
			if(!this.handles[eventName]) {
				this.handles[eventName] = [];
			}
			if(this.handles[arguments[0]]) {
				for(var i = 0; i < this.handles[arguments[0]].length; i++) {
					this.handles[arguments[0]][i](arguments[1]);
				}
			}
		}
	};

	//写入cookie
	var _setCookie = function(name, value, time) {
		var strsec = getsec(time);
		var exp = new Date();
		exp.setTime(exp.getTime() + strsec * 1);
		document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();

		function getsec(str) {
			var val = str.substring(0, str.length - 1);
			var unit = str.substring(str.length - 1, str.length);
			if(unit == "s") {
				return val * 1000;
			} else if(unit == "h") {
				return val * 60 * 60 * 1000;
			} else if(unit == "d") {
				return val * 24 * 60 * 60 * 1000;
			}
		};
	};

	//读取cookie
	var _getCookie = function(name) {
		var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
		if(arr != null) {
			return unescape(arr[2]);
		}
		return null;
	};

	//删除cookies 
	var _delCookie = function(name) {
		var exp = new Date();
		exp.setTime(exp.getTime() - 10);
		var cval = _getCookie(name);
		if(cval != null) {
			document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
		}
	};

	var _getQueryString = function(form, key) {
		var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
		var r = form.location.search.substr(1).match(reg);
		if(r != null) return unescape(r[2]);
		return null;
	};

	var _listToTree = function(data, strlen) {
		var list = [];
		$.extend(true, list, data);

		var idstr = "id";
		var pidstr = "pid";
		var json = [],
			temp = {};
		for(var i = 0; i < list.length; i++) {
			list[i]["name"] = list[i]["text"];
			if(strlen) {
				if(list[i]["text"].length > strlen) {
					list[i]["text"] = list[i]["text"].substr(0, strlen) + "...";
				}
			}
			temp[list[i][idstr]] = list[i];
		}
		for(var j = 0; j < list.length; j++) {
			var tempVp = temp[list[j][pidstr]];
			if(tempVp) {
				if(!tempVp["nodes"]) tempVp["nodes"] = [];
				tempVp["nodes"].push(list[j]);
			} else {
				json.push(list[j]);
			}
		}
		return json;
	};

	//	var _treeToList = function treeToList(list, json, rootID) {
	//		var curID = rootID + list.length;
	//		for(var i = 0; i < json.length; i++) {
	//			var item = $.extend(true, {}, json[i]);
	//			delete item.nodes;
	//
	//			curID++;
	//			item["id"] = curID;
	//			item["pid"] = rootID;
	//			list.push(item);
	//
	//			if(json[i]["nodes"]) {
	//				treeToList(list, json[i]["nodes"], curID);
	//			}
	//		}
	//	};

	var _treeToList = function(list, json, field) {
		treeToList(list, json, "root");

		function treeToList(list, json, rootID) {
			for(var i = 0; i < json.length; i++) {
				var item = $.extend(true, {}, json[i]);
				delete item.nodes;

				item["id"] = item[field];
				item["pid"] = rootID;
				list.push(item);

				if(json[i]["nodes"]) {
					treeToList(list, json[i]["nodes"], item["id"]);
				}
			}
		}
	};

	function _isNumber(val) {
		var regPos = /^\d+(\.\d+)?$/; //非负浮点数
		var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
		if(regPos.test(val) || regNeg.test(val)) {
			return true;
		} else {
			return false;
		}
	};

	function _getUniqueList(arr) {
		var res = [];
		for(var i = 0; i < arr.length; i++) {
			if(res.indexOf(arr[i]) == -1) {
				res.push(arr[i]);
			}
		}
		return res;
	};

	function _getStrLength(val) {
		var len = 0;
		for(var i = 0; i < val.length; i++) {
			var a = val.charAt(i);
			if(a.match(/[^\x00-\xff]/ig) != null) {
				len += 2; //中文算2个字符
			} else {
				len += 1;
			}
		}
		return len;
	};

	function _colorRGBtoHex(color) {
		var rgb = color.split(',');
		var r = parseInt(rgb[0].split('(')[1]);
		var g = parseInt(rgb[1]);
		var b = parseInt(rgb[2].split(')')[0]);
		var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
		return hex;
	};

	//对字符串进行加密   
	function _compileStr(code) {
		var c = String.fromCharCode(code.charCodeAt(0) + code.length);
		for(var i = 1; i < code.length; i++) {
			c += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i - 1));
		}
		return escape(c);
	};
	//字符串进行解密   
	function _uncompileStr(code) {
		code = unescape(code);
		var c = String.fromCharCode(code.charCodeAt(0) - code.length);
		for(var i = 1; i < code.length; i++) {
			c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1));
		}
		return c;
	};

	//全角转半角
	function _SBCtoDBC(str) {
		var tmp = "";
		for(var i = 0; i < str.length; i++) {
			if(str.charCodeAt(i) >= 65281 && str.charCodeAt(i) <= 65374) { // 如果位于全角！到全角～区间内
				tmp += String.fromCharCode(str.charCodeAt(i) - 65248)
			} else if(str.charCodeAt(i) == 12288) { //全角空格的值，它没有遵从与ASCII的相对偏移，必须单独处理
				tmp += ' ';
			} else { // 不处理全角空格，全角！到全角～区间外的字符
				tmp += str[i];
			}
		}
		return tmp;
	};

	function _getNowDate() {
		var nowDate = new Date();
		var day = nowDate.getDate();
console.log(day)
		if(nowDate.getMonth() < 10) {
			var month = "0" + (nowDate.getMonth() + 1);
		}

		if(nowDate.getDate() < 10) {
			day = "0" + nowDate.getDate();
		}
		var datew = nowDate.getFullYear() + "-" + month + "-" + day;
		return datew.toString();
	};

	function _customValidate(column, value) {
		if(!column.cannull) {
			if(!value && value !== 0) {
				return '内容不能为空';
			}
		}
		if(value || value === 0) {
			if(column.coltype == "NUMBER") {
				if(!vw_static.isNumber(Number(value))) {
					return '不是数字类型';
				}
				if(column.maxval && Number(value) > Number(column.maxval)) {
					return '超出最大阈值：' + column.maxval;
				}
				if(column.minval && Number(value) < Number(column.minval)) {
					return '超出最小阈值：' + column.minval;
				}
				if(column.precision && value && value.toString().split(".").length > 1 && value.toString().split(".")[1].length > Number(column.precision)) {
					return '超出最大小数位数：' + column.precision;
				}
			} else if(column.coltype == "VARCHAR2") {
				if(column.txtlength && vw_static.getStrLength(value) > Number(column.txtlength)) {
					return '超出最大文本长度：' + column.txtlength;
				}
				if(column.txtformat) {
					try {
						if(!value.match(column.txtformat)) {
							return column.txtstandard;
						}
					} catch(err) {}
				}
			} else if((column.coltype == "DATE" || column.coltype == "DATETIME")) {
				if(typeof(value) == "string") {
					if(new Date(value) == "Invalid Date") {
						return '无效时间';
					}
				} else if(typeof(value) != "object") {
					return '时间格式错误：（' + column.format + '）';
				}
			}
		}
	};

	function _idToPosition(id) {
		return String.fromCharCode(64 + parseInt(id.split('_')[1]) + 1) + (parseInt(id.split('_')[0]) + 1);
	};

	function _positionToID(position) {
		var col = position.replace(/[0-9]/ig, "").charCodeAt() - 64 - 1;
		var row = position.replace(/[^0-9]/ig, "") - 1;
		return row + '_' + col;
	};

	function _isIntersect(rect1, rect2) {
		var maxX = rect1.left + rect1.width >= rect2.left + rect2.width ? rect1.left + rect1.width : rect2.left + rect2.width;
		var maxY = rect1.top + rect1.height >= rect2.top + rect2.height ? rect1.top + rect1.height : rect2.top + rect2.height;
		var minX = rect1.left <= rect2.left ? rect1.left : rect2.left;
		var minY = rect1.top <= rect2.top ? rect1.top : rect2.top;
		return(maxX - minX <= rect1.width + rect2.width && maxY - minY <= rect1.height + rect2.height);
	};

	function _generateUUID() {
		var d = new Date().getTime();
		if(window.performance && typeof window.performance.now === "function") {
			d += performance.now(); //use high-precision timer if available
		}
		var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = (d + Math.random() * 16) % 16 | 0;
			d = Math.floor(d / 16);
			return(c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
		});
		return uuid;
	};

	function _downloadTextFile(content, filename) {
		var eleLink = document.createElement('a');
		eleLink.download = filename;
		eleLink.style.display = 'none';
		var blob = new Blob([content]);
		eleLink.href = URL.createObjectURL(blob);
		document.body.appendChild(eleLink);
		eleLink.click();
		document.body.removeChild(eleLink);
	};

	function _getNoRepeat(s) {
		return s.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g, "$1$2$4").replace(/,,+/g, ",").replace(/,$/, "").split(",");
	}

	return {
		setCookie: _setCookie,
		getCookie: _getCookie,
		delCookie: _delCookie,
		event: _event,
		hashMap: _hashMap,
		quickSort: quickSort,
		getQueryString: _getQueryString,
		listToTree: _listToTree,
		treeToList: _treeToList,
		isNumber: _isNumber,
		getUniqueList: _getUniqueList,
		getStrLength: _getStrLength,
		colorRGBtoHex: _colorRGBtoHex,
		compileStr: _compileStr,
		uncompileStr: _uncompileStr,
		SBCtoDBC: _SBCtoDBC,
		getNowDate: _getNowDate,
		customValidate: _customValidate,
		idToPosition: _idToPosition,
		positionToID: _positionToID,
		isIntersect: _isIntersect,
		generateUUID: _generateUUID,
		downloadTextFile: _downloadTextFile,
		getNoRepeat: _getNoRepeat
	}
}();